<template>
    <div>
        <div class="title">
            <el-select clearable v-model="operatorId" placeholder="请选择代理商">
                <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.operatorNm"
                        :value="item.operatorId"
                ></el-option>
            </el-select>
            <el-input maxlength="15" style="width:258px;margin-left:20px;" placeholder="搜索设备名/小区名/设备编号"
                      v-model="keyWord"></el-input>

            <el-button @click="searchData" type="primary" style="margin-left:20px;">搜索</el-button>
            <el-button @click="addHandler" type="primary" style="margin-left:20px;">新增</el-button>
            <el-button @click="changeallPort" type="primary" style="margin-left:20px;">开启/关闭充电桩</el-button>
            <el-button style="margin-left:20px;height:40px" type="primary" @click="exporthandler">导出</el-button>
        </div>
        <div class="data">
            <el-table v-loading="loading" :data="tableData" stripe style="width: 100%">
                <el-table-column type="index" label="序号" align="center" min-width="100"></el-table-column>
                <el-table-column prop="id" label="充电桩编号" align="center" min-width="100"></el-table-column>

                <el-table-column prop="pkname" label="充电桩名称" align="center" min-width="100"></el-table-column>
                <el-table-column prop="portCount" label="端口数" align="center" min-width="100"></el-table-column>
                <el-table-column prop="plotName" align="center" label="小区名称  " min-width="80"></el-table-column>
                <el-table-column prop="realName" align="center" label="所属代理商  " min-width="80"></el-table-column>

                <el-table-column prop="s" align="center" label="运行状态 " :formatter="forState"
                                 min-width="80"></el-table-column>
<!--
                <el-table-column prop="runningStatus" align="center" label="运行状态 " :formatter="forState"
                                 min-width="80"></el-table-column>
-->


                <el-table-column prop="totalPowerConsumption" label="设备总耗电量" align="center"
                                 min-width="80"></el-table-column>
                <el-table-column prop="equipTemperature" label="设备温度" align="center" min-width="80"></el-table-column>

                <el-table-column prop="equipCpuTemperature" label="设备cpu温度" align="center"
                                 min-width="100"></el-table-column>
                <el-table-column prop="simCard" label="SIM卡序列号" align="center" min-width="100"></el-table-column>
                <el-table-column prop="simDueTime" label="SIM卡到期时间" align="center" min-width="100"></el-table-column>
                <el-table-column prop="useCount" label="使用频率" align="center" min-width="100"></el-table-column>
                <el-table-column prop="cpFeeType" :formatter="cpFeeType" label="是否收费" align="center"
                                 min-width="100"></el-table-column>
                <el-table-column label="操作" align="center" min-width="140">
                    <template slot-scope="scope">
                        <!--            <el-link @click="price(scope.row)" icon="el-icon-edit">价格编辑</el-link>-->
                        <el-link @click="ruleEditHandler(scope.row)" icon="el-icon-edit">规则编辑</el-link>
                        <el-link @click="editCardHandler(scope.row)" icon="el-icon-edit">编辑</el-link>
                        <el-link @click="port(scope.row)">端口管理</el-link>
                        <!-- <el-link @click="deleteHandler(scope.rosw)">删除</el-link> -->
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-size="pageSize"
                    :total="total"
            ></el-pagination>
        </div>
        <el-dialog id="rulePopupModal" title="规则编辑" :visible.sync="ruleDialogVisible" width="30%">
            <el-form ref="form_rule" :model="ruleFormData" label-width="150px" :rules="ruleFormRule">

                <el-form-item class="nav-form-item" label="卡规则" prop="cardRuleId">
                    <el-select v-model="ruleFormData.cardRuleId" style="width:120px" placeholder="请选择卡规则">
                        <el-option v-for="item in cardList" :label="item.changeName" :value="item.id"
                                   :key="item.id"></el-option>
                    </el-select>
                    <span class="status-name" style="color: rgb(49, 209, 158);cursor: pointer"
                          @click="editRule('card')">去编辑选中规则</span>
                </el-form-item>
                <el-form-item class="nav-form-item" label="公众号规则" prop="wxRuleId">
                    <el-select v-model="ruleFormData.wxRuleId" style="width:120px" placeholder="请选择区公众号规则">
                        <el-option v-for="item in gzhList" :label="item.changeName" :value="item.id"
                                   :key="item.id"></el-option>
                    </el-select>
                    <span class="status-name" style="color: rgb(49, 209, 158);cursor: pointer" @click="editRule('wx')">去编辑选中规则</span>

                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="ruleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="ruleConfimHandler">确 定</el-button>
      </span>
        </el-dialog>

        <el-dialog id="popupMoal" :title="popUpModalTitle" :visible.sync="dialogVisible" width="60%">
            <el-form ref="form" :model="formData" label-width="150px" :rules="formRule">
                <el-form-item class="nav-form-item" label="充电桩编号 " prop="id">
                    <el-input
                            maxlength="8"
                            :disabled="!isAdd"
                            v-model="formData.id"
                            style="width:300px;"
                            placeholder="请输入充电桩编号"
                            clearable
                    />
                </el-form-item>
                <el-form-item class="nav-form-item" label="充电桩名称" prop="pkname">
                    <el-input maxlength="15" v-model="formData.pkname" style="width:300px;" placeholder="请输入充电桩名称"/>
                </el-form-item>
                <el-form-item class="nav-form-item" label="所属小区ID" prop="province">
                    <el-select
                            style="width:120px"
                            v-model="province"
                            @change="selProvince"
                            placeholder="请选择省份"
                    >
                        <el-option
                                v-for="item in provinceList"
                                :label="item.name"
                                :value="item.id"
                                :key="item.id"
                        ></el-option>
                    </el-select>
                    <el-select @change="selCity" style="width:120px" v-model="city" placeholder="请选择市">
                        <el-option v-for="item in cityList" :label="item.name" :value="item.id"
                                   :key="item.id"></el-option>
                    </el-select>
                    <el-select @change="selArea" style="width:120px" v-model="area" placeholder="请选择区">
                        <el-option v-for="item in areaList" :label="item.name" :value="item.id"
                                   :key="item.id"></el-option>
                    </el-select>
                    <el-select @change="selPlot" style="width:120px" v-model="polt" placeholder="请选择小区" prop="plotName"
                               v-if="poltList.length">
                        <el-option v-for="item in poltList" :label="item.plotName" :value="item.id"
                                   :key="item.id"></el-option>
                    </el-select>
                    <el-input maxlength="15" v-model="formData.plotName" style="width:200px;" placeholder="请输入小区名"
                              v-else/>
                </el-form-item>
                <el-form-item class="nav-form-item" label="端口数" prop="portCount">
                    <el-input
                            maxlength="3"
                            max="100"
                            v-model="formData.portCount"
                            style="width:300px;"
                            placeholder="请输入端口数"
                    />
                </el-form-item>
                <el-form-item class="nav-form-item" label="SIM卡序列号" prop="simCard">
                    <el-input maxlength="20" v-model="formData.simCard" style="width:300px;" placeholder="请输入SIM卡序列号"/>
                </el-form-item>
                <el-form-item label="SIM卡到期时间" prop="simDueTime">
                    　
                    <el-date-picker
                            　　v-model="formData.simDueTime"
                            　　type="datetime"
                            　　value-format="yyyy-MM-dd HH:mm:ss"
                            format="yyyy-MM-dd HH:mm:ss"
                            　　>
                    </el-date-picker>
                </el-form-item>
                <el-form-item class="nav-form-item" label="所属代理商">
                    <el-select v-model="formData.userId" placeholder="所属代理商">
                        <el-option
                                v-for="item in agentData"
                                :label="item.operatorNm"
                                :value="item.operatorId"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="nav-form-item" label="是否收费" prop="name">
                    <el-select style="width:200px" v-model="formData.cpFeeType" placeholder="请选择">
                        <el-option label="收费" value="2001"></el-option>
                        <el-option label="免费" value="2002"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="nav-form-item" label="运行状态" prop="name">
                    <el-select style="width:200px" v-model="formData.runningStatus" placeholder="请选择">
                        <el-option label="运行" value="0"></el-option>
                        <el-option label="离线" value="1"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">取 消</el-button>
        <el-button :disabled="isDisable" type="primary" @click="confimHandler">确 定</el-button>
      </span>
        </el-dialog>


        <el-dialog id="allPortModal" title="端口开启/关闭" :visible.sync="allPortVisible" width="30%">
            <el-form ref="form_allPort" :model="allPortFormData" label-width="150px" :rules="allPortFormRule">
                <el-form-item class="nav-form-item" label="充电桩编号" prop="code">
                    <el-input
                            maxlength="10"
                            max="100"
                            v-model="allPortFormData.code"
                            style="width:200px;"
                            placeholder="请输入充电桩编号"
                    />
                </el-form-item>
                <el-form-item class="nav-form-item" label="选择开关" prop="type">
                    <el-select v-model="allPortFormData.type" style="width:200px" placeholder="请选择开关">
                        <el-option v-for="item in kgList" :label="item.name" :value="item.id"
                                   :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="allPortVisible = false">取 消</el-button>
                <el-button type="primary" @click="allPortConfimHandler">确 定</el-button>
              </span>
        </el-dialog>

    </div>
</template>
<script>
    import {
        getChargingPileList,
        delPromotion,
        addPile,
        editPile,
        setPileRule
    } from '@/api/device'
    import {getToken} from '@/utils/auth'
    import {getProvinceList, getCityList, getPoltList} from '@/api/common'
    import {getDataScopeList} from '@/api/user'
    import {getOperatorSelect} from '@/api/operator'
    import {getRuleList} from '@/api/rule'
    import {allPort} from "../../api/port";

    export default {
        data() {
            return {
                url: process.env.VUE_APP_BASE_API,
                polt: '',
                poltList: [],
                area: '',
                areaList: '',
                city: '',
                cityList: [],
                province: '',
                provinceList: [],
                isDisable: false,
                allPortVisible: false,
                dialogVisible: false,
                ruleDialogVisible: false,
                gzhList: [],
                cardList: [],
                operatorId: this.$route.query.operatorId,
                keyWord: '',
                id: '',
                isAdd: true,
                search: '',
                tableData: [],
                page: 1,
                pageSize: 10,
                loading: true,
                allPortFormData: {
                    type: "",
                    code: ""
                },
                ruleFormData: {
                    cardRuleId: "",
                    wxRuleId: "",
                    Id: ""
                },
                formData: {
                    id: null,
                    pkname: '',
                    plot: '',
                    plotName: '',
                    portCount: null,
                    simCard: '',
                    simDueTime: "",
                    userId: "",
                    runningStatus: '',
                    cpFeeType: "",
                    regionCode: ""
                },
                total: 0,
                agentData: [],
                options: [],
                kgList:[
                    {id:'1',name:'打开'},
                    {id:'0',name:'关闭'}
                ],
                formRule: {
                    id: [{required: true, message: '请输入充电桩编号', trigger: 'blur'}],
                    pkname: [{required: true, message: '请输入充电桩名称', trigger: 'blur'}],
                    simCard: [{required: true, message: '请输入卡号', trigger: 'blur'}],
                    plotName: [{required: true, message: '请选择小区', trigger: 'blur'}],
                    portCount: [{required: true, message: '请输入端口数', trigger: 'blur'}],
                    simDueTime: [{required: true, message: '请输入到期时间', trigger: 'blur'}],
                    runningStatus: [{required: true, message: '请选择运行状态', trigger: 'blur'}]
                },
                allPortFormRule: {
                    id: [{required: true, message: '请输入充电桩编号', trigger: 'blur'}],
                    type: [{required: true, message: '请选择选择开关', trigger: 'blur'}],
                },
                ruleFormRule: {
                    wxRuleId: [{required: true, message: '请选择公众号规则', trigger: 'blur'}],
                    cardRuleId: [{required: true, message: '请选择卡规则', trigger: 'blur'}],
                },
                props: {
                    value: 'id',
                    label: 'name'
                },
                popUpModalTitle: "新增"
            }
        },
        created() {
            this.getDataScopeList()
            this.getProvinceList()
            this.getDataList()
            this.getAgentList();
        },
        watch: {
            polt: function (v) {
                this.formData.plot = v;
            },
            'formData.portCount': {
                handler: function (v) {
                    if (v > 100) {
                        this.formData.portCount = 100
                    }
                }
            }
        },
        methods: {
            forState(row) {
                if ((row.m || 31)<=30) {
                    return '运行';
                }else{
                    return '离线';
                }
//                if (row.runningStatus == 0) {
//                    return '运行'
//                } else if (row.runningStatus == 1) {
//                    return '离线'
//                }
            },
            cpFeeType(row) {
                if (row.cpFeeType == 2001) {
                    return '收费'
                } else if (row.cpFeeType == 2002) {
                    return '免费'
                }
            },
            editRule(type) {
                if (type === 'wx') {
                    if (this.ruleFormData.wxRuleId) {
                        this.$router.push({
                            path: '/rules/price',
                            query: {
                                id: this.ruleFormData.wxRuleId
                            }
                        })
                    } else {
                        this.$message({
                            message: '请先选择规则',
                            type: 'fail'
                        })
                    }
                }
                if (type === 'card') {
                    if (this.ruleFormData.cardRuleId) {
                        this.$router.push({
                            path: '/rules/price',
                            query: {
                                id: this.ruleFormData.cardRuleId
                            }
                        })
                    } else {
                        this.$message({
                            message: '请先选择规则',
                            type: 'fail'
                        })
                    }
                }
            },
            getRules(userId) {
                getRuleList({ruleType: 10002, pageNo: 1, pageSize: 20, userId: userId}).then(res => {
                    this.gzhList = [...res.data.records]
                })
                getRuleList({ruleType: 10001, pageNo: 1, pageSize: 20, userId: userId}).then(res => {
                    this.cardList = [...res.data.records]
                })
            },
            price(row) {
                if (row.wxRuleId) {
                    var id = row.wxRuleId
                } else {
                    alert("暂未分配微信规则")
                    return false
                }
                this.$router.push({
                    path: '/rules/price',
                    query: {
                        id: id
                    }
                })
            },
            selArea(val) {
                let param = {
                    regionCode: val
                }
                this.formData.regionCode = val
                this.formData.plotName = ''
                getPoltList(param).then(res => {
                    this.poltList = [...res.data]
                    this.poltList.push({"id": -1, plotName: "自定义输入小区"})
                    this.polt = ''
                })
            },
            selPlot(val) {
                if (val == -1) {
                    this.poltList = []
                }
            },
            selCity(val) {
                let param = {
                    pid: val
                }
                getCityList(param).then(res => {
                    this.areaList = [...res.data]
                    this.area = ''
                })
            },
            exporthandler() {
                if (typeof this.operatorId === "undefined") {
                    this.operatorId = ''
                }
                window.location.href =
                    this.url +
                    '/chargingpile/export?keyWord=' +
                    this.keyWord +
                    '&userId=' +
                    this.operatorId
            },
            selProvince(val) {
                let param = {
                    pid: val
                }
                getCityList(param).then(res => {
                    this.cityList = [...res.data]
                    this.city = ''
                })
            },
            getProvinceList() {
                getProvinceList().then(res => {
                    this.provinceList = [...res.data]
                })
            },
            getAgentList() {
                getOperatorSelect().then(res => {
                    this.agentData = [...res.data]
                })
            },
            loadNode(node, resolve) {
                if (node.level === 0) {
                    getProvinceList().then(res => {
                        return resolve(res.data)
                    })
                } else if (node.level === 1) {
                    let param = {
                        pid: node.data.id
                    }
                    getCityList(param).then(res => {
                        resolve(res.data)
                    })
                } else if (node.level === 2) {
                    let param = {
                        regionCode: node.data.id
                    }
                    getPoltList(param).then(res => {
                        res.data.forEach(element => {
                            element.leaf = false
                        })
                        resolve(res.data)
                    })
                }
            },
            getDataScopeList() {
                getDataScopeList().then(res => {
                    if (res.data && res.data.length > 0) {
                        this.options = [...res.data]
                    }
                })
            },
            searchData() {
                this.page = 1
                this.getDataList()
            },
            getDataList() {
                this.loading = true
                let param = {
                    keyWord: this.keyWord,
                    userId: this.operatorId,
                    pageNo: this.page,
                    pageSize: this.pageSize
                }
                getChargingPileList(param).then(res => {
                    if (res.data && res.data.records.length >= 0) {
                        this.tableData = [...res.data.records]
                        this.total = res.data.total
                    }

                    this.loading = false
                })
            },
            handleCurrentChange(val) {
                this.page = val
                this.getDataList()
            },
            addHandler() {
                this.isAdd = true
                this.formData.id = null
                this.formData.pkname = ''
                this.formData.plot = ''

                this.formData.portCount = ''
                this.formData.simCard = ''
                this.formData.simDueTime = ''
                this.formData.regionCode = ''
                this.formData.runningStatus = ''
                this.formData.cpFeeType = ''

                this.province = ''
                this.city = ''
                this.area = ''
                this.polt = ''
                this.formData.portCount = 20
                this.popUpModalTitle = "新增"
                this.dialogVisible = true
                if (this.$refs.form) {
                    this.$refs.form.clearValidate();
                }
            },
            changeallPort(){
                this.allPortFormData.code = null
                this.allPortFormData.type = ''
                this.allPortVisible = true
            },
            allPortConfimHandler() {
                this.$refs.form_allPort.validate(valid => {
                    if (valid) {
                        allPort(this.allPortFormData).then(res => {
                            if (res.message.code == -1 || res.message.code == -2 || res.message.code == -3) {
                                this.$message.error(res.message.message)
                            } else {
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                })
                                this.allPortVisible = false;
                                this.getDataList()
                            }
                        })
                    }
                })
            },
            ruleConfimHandler() {
                this.$refs.form_rule.validate(valid => {
                    if (valid) {
                        setPileRule(this.ruleFormData).then(res => {
                            if (res.message.code == 0) {
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                })
                                this.getDataList()
                            } else {
                                this.$message.error(res.message.message)
                            }
                            this.ruleDialogVisible = false
                        })
                    }
                })
            },
            confimHandler() {
                console.log(12345)
                if (!this.formData.plot && !this.formData.plotName) {
                    this.$message.error("请选择小区或者输入自定义小区")
                    return
                }
                this.$refs.form.validate(valid => {
                    if (valid) {
                        if (this.isAdd) {
                            this.addCard()
                        } else {
                            this.editCard()
                        }
                    }
                })
            },
            initSelect(province, city, region) {
                var that = this
                let param = {
                    pid: province
                }
                getCityList(param).then(res => {
                    this.cityList = [...res.data]
                    let param = {
                        pid: city
                    }
                    getCityList(param).then(res => {
                        this.areaList = [...res.data]
                        let param = {
                            regionCode: region
                        }
                        getPoltList(param).then(res => {
                            this.poltList = [...res.data]
                            this.poltList.push({"id": -1, plotName: "自定义输入小区"})
                        })
                    })
                })
            },
            ruleEditHandler(row) {
                this.getRules(row.userId);
                this.ruleFormData.wxRuleId = row.wxRuleId
                this.ruleFormData.cardRuleId = row.cardRuleId
                this.ruleFormData.Id = row.id
                this.ruleDialogVisible = true
            },
            editCardHandler(row) {
                if (this.$refs.form) {
                    this.$refs.form.clearValidate();
                    this.$refs.form.resetFields();
                }
                this.initSelect(row.provinceCode, row.cityCode, row.regionCode)
                this.isAdd = false
                this.formData.id = row.id
                this.formData.pkname = row.pkname
                this.formData.plot = row.plot
                this.formData.portCount = row.portCount
                this.formData.simCard = row.simCard
                this.formData.simDueTime = row.simDueTime
                this.formData.userId = row.userId
                this.formData.regionCode = row.regionCode
                this.formData.runningStatus = row.runningStatus
                this.formData.cpFeeType = row.cpFeeType
                this.province = row.province
                this.city = row.city
                this.area = row.regionName
                this.polt = row.plot
                this.dialogVisible = true
                this.popUpModalTitle = "编辑"
            },
            editCard() {
                this.isDisable = true
                if (this.formData.plotName) {
                    this.formData.plot = null
                }
                editPile(this.formData).then(res => {
                    if (res.message.code == 0) {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        this.dialogVisible = false
                        this.getDataList()
                    } else {
                        this.$message.error(res.message.message)
                    }
                    this.isDisable = false
                })
            },
            addCard() {
                this.isDisable = true
                if (this.formData.plotName) {
                    this.formData.plot = null
                }
                addPile(this.formData).then(res => {
                    if (res.message.code == -1) {
                        this.$message.error(res.message.message)
                    } else {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        this.dialogVisible = false
                        this.getDataList()
                    }
                    this.isDisable = false
                })
            },
            port(row) {
                this.$router.push({
                    path: 'portList',
                    query: {
                        id: row.id
                    }
                })
            }
        }
    }
</script>
<style scoped>
    .title {
        margin-left: 20px;
        margin-top: 20px;
        display: flex;
        flex-direction: row;
    }

    .data {
        margin-left: 20px;
        margin-top: 20px;
        margin-right: 10px;
    }

    .tree {
        position: absolute;
        z-index: 10;
        top: 40px;
        width: 300px;
    }

    .is-disabled .el-input__inner {
        background: #22425b !important;
        border-color: #22425b !important;
    }
</style>
